import { createStore } from "vuex";
import vuexPers from "vuex-persistedstate";
//持久化插件
export default createStore({
  state: {
    shopcar: [],
    checked: false,
  },
  mutations: {
    add(state, obj) {
      console.log(obj);
      let flag = false;
      state.shopcar.forEach((item) => {
        if (item.id == obj.id) {
          item.num += obj.num;
          //为什么不是++ 这里在添加购物车的时候可以选择数量 选了四个就加四个
          flag = true;
        }
      });

      if (flag == false) {
        state.shopcar.push(obj);
        state.checked = false;
      }
    },
    //添加购物车
    changeItem(state) {
      state.checked = state.shopcar.every((item) => item.status == true);
    },
    //点击上面的复选框按钮
    checkAll(state) {
      state.shopcar.forEach((item) => (item.status = state.checked));
    },
    //点击全选按钮
    clear(state) {
      state.shopcar = state.shopcar.filter((item) => item.status == false);
      state.checked = false;
    }, //选中删除的方法 把不删的 status是false的留下来
  },
  actions: {},
  modules: {},
  plugins: [vuexPers()],
  getters: {
    allPrice(state) {
      let all = 0;
      state.shopcar.forEach((item) => {
        if (item.status == true) {
          all += item.num * item.price;
        }
      });
      return all;
    },
    //计算选中的总价
    allNum(state) {
      let all = 0;
      state.shopcar.forEach((item) => {
        all += item.num;
      });
      return all;
    },
    //计算 所有商品的数量
  },
});
